//
//  WlisDisplayBaseVCViewController.swift
//  Swift_missScarlett
//
//  Created by xmg on 16/8/25.
//  Copyright © 2016年 wlis. All rights reserved.
//

import UIKit
let cellID = "baseCell"
class WlisDisplayBaseVC: UIViewController {

    var titleScrollView : UIScrollView?;
    var collectionView : UICollectionView?;
    var tempBtn : UIButton?;
    var isInitial : Bool = false
    
    lazy var buttons : [UIButton] = [UIButton]()
    lazy var uiderView : UIView = {
        let uiderView = UIView()
        uiderView.backgroundColor = UIColor.redColor()
        self.titleScrollView?.addSubview(uiderView)
        return uiderView
    }()
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setUpBottomContentView()
        setUpTopTitleView()
        
        self.automaticallyAdjustsScrollViewInsets = false
    }

    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        if isInitial == false{
        self.setUpAllTitle()
            isInitial = true
        }
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    
    }

}

// MARK: - 设置顶部和底部
extension WlisDisplayBaseVC {

    /** 设置顶部的内容View */
    func setUpTopTitleView(){
    
        let y :CGFloat = self.navigationController?.navigationBarHidden == true ? 20 : 64
        let ScrollView = UIScrollView(frame: CGRectMake(0,y,WlisScreenW,35))
        ScrollView.scrollsToTop = false
        ScrollView.backgroundColor = UIColor(white: 1, alpha: 0.8)
        self.titleScrollView = ScrollView
        self.view.addSubview(ScrollView)
    }
    
    /** 设置底部内容View */
    func setUpBottomContentView(){
    
        let y :CGFloat = 0
        let h :CGFloat = WlisScreenH
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .Horizontal
        layout.itemSize = CGSizeMake(WlisScreenW, h)
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        
        let contentCollectionView = UICollectionView(frame:
            CGRectMake(0, y, WlisScreenW, h), collectionViewLayout: layout)
        self.collectionView = contentCollectionView
        self.collectionView?.scrollsToTop = false
        self.view.addSubview(contentCollectionView)
        self.collectionView?.dataSource = self
        self.collectionView?.delegate = self
        
        /** 注册cell */
        self.collectionView?.registerClass(UICollectionViewCell.classForCoder(), forCellWithReuseIdentifier: cellID)
        self.collectionView?.pagingEnabled = true
        self.collectionView?.showsHorizontalScrollIndicator = false
        
    }
}

// MARK: - 设置标题选中点击
extension WlisDisplayBaseVC{
    /** 设置标题 */
    func setUpAllTitle(){
    
        let count : Int = self.childViewControllers.count
        let btnW = WlisScreenW / CGFloat(count)
        let btnH : CGFloat = (self.titleScrollView?.height)!
        var btnX : CGFloat;
        for i in 0 ..< count{
            btnX = CGFloat(i) * btnW
            let  btn = UIButton(frame: CGRectMake(btnX, 0, btnW, btnH))
            btn.tag = i
            let title = self.childViewControllers[i].title
            btn.setTitle(title, forState: .Normal)
            btn.setTitleColor(UIColor.blackColor(), forState: .Normal)
            btn.setTitleColor(UIColor.redColor(), forState: .Selected)
            btn.addTarget(self, action: "titleClick:", forControlEvents: .TouchUpInside)
            self.titleScrollView?.addSubview(btn)
            buttons.append(btn)
            
        }
    }
    @objc func titleClick(btn:UIButton){
    
        /** 滚动到对应的位置 */
        let i = btn.tag
        /** 是否重复点击 */
        if i == self.tempBtn?.tag{
        
            /** 取出对应的子控件器 */
            let childVc = self.childViewControllers[i]
            
            /** 加载最新的数据 */
            (childVc as! WlisThemeBaseVC).tableView.mj_header.beginRefreshing()
        }
        
        self.selectButton(btn)
        
        let offsetX :CGFloat = CGFloat(i) * WlisScreenW
        self.collectionView?.contentOffset = CGPointMake(offsetX, 0)
        
        var index = 0;
        for childVc in self.childViewControllers{
        
            (childVc.view as! UITableView).scrollsToTop = (index == i)
            index += 1
        }
    }
    
    
    
    func selectButton(btn : UIButton){
        tempBtn?.selected = false
        btn.selected = true
        tempBtn = btn
        
        /** 显示下划线滚动 */
        let h : CGFloat = 1.5
        let x = btn.convertPoint((btn.titleLabel?.frame.origin)!, toView: self.titleScrollView).x
        let y = CGRectGetMaxY((btn.titleLabel?.frame)!) + h
        let w : CGFloat = (btn.titleLabel?.width)!
        
        if self.uiderView.frame.origin.x > 0{
        
            UIView.animateWithDuration(0.25, animations: { () -> Void in
                self.uiderView.frame = CGRectMake(x, y, w, h)
                self.uiderView.x = x
            })
        }
        
    }
}
extension WlisDisplayBaseVC:UICollectionViewDataSource{

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.childViewControllers.count
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellID, forIndexPath: indexPath)
        (cell.contentView.subviews as NSArray).enumerateObjectsUsingBlock { (objc, i, stop) -> Void in
            (objc as! UIView).removeFromSuperview()
        }
        let vc = self.childViewControllers[indexPath.row]
        if vc.view.superview == nil{
        vc.view.frame = cell.bounds
        }
        cell.contentView.addSubview(vc.view)
        return cell
    }
}
extension WlisDisplayBaseVC: UICollectionViewDelegate{

    func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
        let i = scrollView.contentOffset.x / WlisScreenW
        
        let button =  buttons[Int(i)]
        self.selectButton(button)
    }
}
